using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using AutoGear.BLL;
using ECommerce.Library.Web;
using ECommerce.Library.DataStructure;
using ECommerce.Library.ECommerce;
using ECommerce.Library;
using Entity;
using AutoGear.BLL.Exceptions;
using System.Net;
using System.IO;
using System.Text;



public partial class order_summary : SitePublicBasePage
{
    ProductPurchaseOrder _productPurchaseOrder;
    private ProductPurchaseOrder PurchaseOrder
    {
        get
        {
            if (_productPurchaseOrder == null)
            {
                BuildData();
            }
            return _productPurchaseOrder;
        }
    }


    private bool IsFraightApplicable
    {
        get
        {
            return Convert.ToBoolean(ViewState["_IsFraightApplicable"].ToString());
        }
        set
        {
            ViewState["_IsFraightApplicable"] = value;
        }
    }
    public static bool IsValidShippingTime
    {
        get
        {
            return DateTime.Now.Hour >= 11 ? false : true;
        }
    }


    public static string _CUSTOMER_CODE
    {
        get
        {
            return ConfigurationManager.AppSettings["_CUSTOMER_CODE"].ToString();
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        uccResponseMessage.Visible = false;
        if (!Page.IsPostBack)
        {

            CheckoutStepsValidate();
            BuildData();
            BindData();
        }
    }



    private void CheckoutStepsValidate()
    {
        ShoppingCart cart = AutoGearSessionManager.ShoppingCart;
        if (cart == null || (cart.CartItems.Count <= 0 && cart.GiftItems.Count <= 0))
            Response.Redirect(string.IsNullOrEmpty(SupplierId) ? AutoGear.BLL.CustomSiteMap.ShoppingCart : "~/partner/" + SupplierId + "/shopping-cart.aspx");

        if (AutoGearSessionManager.CheckoutSteps < CheckoutSteps.PreCheckout)
        {
            Response.Redirect(string.IsNullOrEmpty(SupplierId) ? AutoGear.BLL.CustomSiteMap.ShoppingCart : "~/partner/" + SupplierId + "/shopping-cart.aspx");
        }

        ContentPlaceHolder ph = (ContentPlaceHolder)this.Master.Master.FindControl("cphMiddleContent");

        Literal litPageTitle = (Literal)ph.FindControl("litPageTitle");
        Literal litCurrentPage = (Literal)ph.FindControl("litCurrentPage");

        if (litPageTitle != null)
        {
            litCurrentPage.Text = litPageTitle.Text = "Order Summary";

        }

    }
    protected void BuildData()
    {
        this._productPurchaseOrder = new ProductPurchaseOrder();
        ShoppingCart cart = AutoGearSessionManager.ShoppingCart;
        this._productPurchaseOrder.ShoppingCart = cart;
        this._productPurchaseOrder.ProductTax = AutoGearSessionManager.StateTax;
        this._productPurchaseOrder.ProductShipping = AutoGearSessionManager.ProductShipping;
        this._productPurchaseOrder.Coupon = AutoGearSessionManager.Coupon;
        this._productPurchaseOrder.ShoppingCart = cart;

    }
    protected void BindData()
    {
        //bind user custom control Dropdownlist
        uccBillingCountry.DataBind();
        uccBillingState.DataBind();
        uccShippingCountry.DataBind();
        uccShippingState.DataBind();
        uccUPSShippingMethodDropDownList.DataBind();
        if (SessionManager.IsUserLoggedIn)
        {
            SiteUser siteUser = SessionManager.LoggedUser;
            if (siteUser is CustomerUser)
            {
                CustomerUser customerUser = siteUser as CustomerUser;
                UserProfile profile = customerUser.Profile;
                tbxBillingFirstName.Text = profile.BillingAddress.FirstName;
                tbxBillingLastName.Text = profile.BillingAddress.LastName;
                tbxBillingPhone.Text = profile.BillingAddress.TelephoneNumber;
                tbxBillingEmailAddress.Text = profile.BillingAddress.EmailAddress;
                tbxBillingAddressLine1.Text = profile.BillingAddress.AddressLine1;
                tbxBillingAddressLine2.Text = profile.BillingAddress.AddressLine2;
                tbxBillingCity.Text = profile.BillingAddress.City;
                uccBillingState.Items.FindByText(profile.BillingAddress.AddressState).Selected = true;
                tbxBillingZipCode.Text = profile.BillingAddress.ZipCode;
                uccBillingCountry.Items.FindByText(profile.BillingAddress.AddressCountry).Selected = true;

                tbxShippingFirstName.Text = profile.ShippingAddress.FirstName;
                tbxShippingLastName.Text = profile.ShippingAddress.LastName;
                tbxShippingPhone.Text = profile.ShippingAddress.TelephoneNumber;
                tbxShippingEmailAddress.Text = profile.ShippingAddress.EmailAddress;
                tbxShippingAddressLine1.Text = profile.ShippingAddress.AddressLine1;
                tbxShippingAddressLine2.Text = profile.ShippingAddress.AddressLine2;
                tbxShippingCity.Text = profile.ShippingAddress.City;
                uccShippingState.Items.FindByText(profile.ShippingAddress.AddressState).Selected = true;
                tbxShippingZipCode.Text = profile.ShippingAddress.ZipCode;
                uccShippingCountry.Items.FindByText(profile.ShippingAddress.AddressCountry).Selected = true;

                //dllShipping.Items.Clear();
                ReadWriteCustomCollection<KeyValuePair<string, string>> addressbook = AddressBook.GetKeyValAddressBook(SessionManager.LoggedUser.UserId);
                foreach (KeyValuePair<string, string> add in addressbook)
                {
                    ddlShipp.Items.Add(new System.Web.UI.WebControls.ListItem(add.Key, add.Value));

                }
                //Load_shipping_info(true);
            }
        }

        BindShoppingCart();
        CalculateAmounts();

        DropDownListPaymentType.SelectedValue = "2";
        pnlGiftCertificateEntry.Visible = false;
        pnlCreditCardEntry.Visible = true;
    }
    private void Load_shipping_info(bool initial)
    {
        if (ddlShipp.SelectedValue != "" && ddlShipp.SelectedValue != "NA")
        {
            ReadWriteCustomCollection<AddressBook> data = null;
            string sqlCondition = string.Empty;
            if (initial && ddlShipp.SelectedValue == "")
            {
                sqlCondition += "IsDefault=1 AND UserId='" + SessionManager.LoggedUser.UserId + "'";
            }
            else
            {
                sqlCondition += " AddressBookId ='" + ddlShipp.SelectedValue + "'";
            }
            data = AddressBook.GetBackendAddressBookListByCondition(sqlCondition, "AddressBookId", 0, 10);
            if (data != null && data.Count > 0)
            {
                tbxShippingFirstName.Text = data[0].UserFirstName;
                tbxShippingLastName.Text = data[0].UserLastName;
                tbxShippingPhone.Text = data[0].UserTelephone1;
                tbxShippingAddressLine1.Text = data[0].UserAddressLine1;
                tbxShippingAddressLine2.Text = data[0].UserAddressLine2;
                tbxShippingEmailAddress.Text = data[0].UserEmailAddress;
                tbxShippingCity.Text = data[0].UserCity;
                tbxShippingZipCode.Text = data[0].UserZip;
                uccShippingState.SelectedIndex = uccShippingState.Items.IndexOf(uccShippingState.Items.FindByText(data[0].UserState));
                uccShippingCountry.SelectedIndex = uccShippingCountry.Items.IndexOf(uccShippingCountry.Items.FindByText(data[0].UserCountry));
            }
        }
    }
    private void CalculateAmounts()
    {
        BindSubTotal();
        BindCouponDiscount();
        double shippingCost = 0.00;
        if (uccUPSShippingMethodDropDownList.SelectedItem.Value != "00")
        {
            if (uccUPSShippingMethodDropDownList.SelectedItem.Value == "02")
            {
                if (string.IsNullOrEmpty(this.SupplierId))
                {
                    if (SiteSettings.IsGroundShippingFree)
                    {
                        if (PurchaseOrder.ShoppingCart.SubTotal >= SiteSettings.GroundShippingAmount)
                        {
                            shippingCost = Convert.ToDouble("0");
                            PurchaseOrder.ProductShipping.ProductShippingCost = shippingCost;
                        }
                        else
                        {
                            CalculateShippingCost();
                        }
                    }
                    else
                    {
                        CalculateShippingCost();
                    }
                }
                else
                {
                    // Free shipping Calculation For partner
                    ECommerce.DAL.CustomCollection<TblBrandOptions> options = TblBrandOptions.GetTblBrandOptionsByProductBrandId(this._PartnerID);
                    if (options != null && options.Count > 0)
                    {
                        TblBrandOptions option = options[0];
                        if (option.IsGroundShippingFree)
                        {
                            if (PurchaseOrder.ShoppingCart.SubTotal >= Convert.ToDouble(option.GroundShippingAmount))
                            {
                                shippingCost = Convert.ToDouble("0");
                                PurchaseOrder.ProductShipping.ProductShippingCost = shippingCost;
                            }
                            else
                            {
                                CalculateShippingCost();
                            }
                        }
                        else
                        {
                            CalculateShippingCost();
                        }
                    }
                }



            }
            else
            {
                CalculateShippingCost();
            }
        }

        BindProductShippingCost();
        BindTax();
        BindGrossTotal();
    }
    private void BindCouponDiscount()
    {
        lblDiscount.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(PurchaseOrder.CouponDiscount);
    }
    private void BindGrossTotal()
    {
        ViewState["FinalTotalPrice"] = PurchaseOrder.TotalAmount;
        //lblTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(PurchaseOrder.TotalAmount + Convert.ToDouble(lblShippingHandling.Text.Replace("$", "")));
        lblTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(PurchaseOrder.TotalAmount);
    }
    protected void BindProductShippingCost()
    {

        lblShippingHandling.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(PurchaseOrder.ProductShipping.ProductShippingCost);
        uplShippingCost.Update();
    }
    protected void BindTax()
    {
        if (uccBillingState.SelectedValue != null)
        {
            StateTax stTax = new StateTax();
            TblTax taxCalculated = TblTax.GetTax(tbxBillingCity.Text.Trim(), uccBillingState.SelectedItem.Value);
            if (taxCalculated != null)
            {
                stTax.Tax = Convert.ToDouble(taxCalculated.TAX_RATE_TOTAL.ToString().Trim());
                if (String.IsNullOrEmpty(taxCalculated.TAX_FRT.Trim()))
                {
                    IsFraightApplicable = false;
                }
                else
                {
                    IsFraightApplicable = taxCalculated.TAX_FRT.Trim() == "N" ? false : true;
                }
            }
            else
            {
                stTax.Tax = 0;
            }

            PurchaseOrder.ProductTax = stTax;
        }

        lblTax.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(PurchaseOrder.ShoppingCart.SubTotal * PurchaseOrder.ProductTax.Tax / 100);
    }
    protected void BindSubTotal()
    {
        lblSubTotal2.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(PurchaseOrder.ShoppingCart.SubTotal + PurchaseOrder.ShoppingCart.GiftSubTotal);
    }
    protected void BindShoppingCart()
    {

        if (PurchaseOrder.ShoppingCart.CartItems.Count > 0 || PurchaseOrder.ShoppingCart.GiftItems.Count > 0)
        {
            if (PurchaseOrder.ShoppingCart.CartItems.Count == 0)
            {
                //lblNoProduct.Visible = true;
                rptShoppingCart.Visible = false;
                pnlEmptyCart.Visible = true;
            }
            else
            {
                rptShoppingCart.DataSource = PurchaseOrder.ShoppingCart.CartItems;
                rptShoppingCart.DataBind();
            }

            if (PurchaseOrder.ShoppingCart.GiftItems.Count == 0)
            {
                //lblNoGift.Visible = true;
                rptShoppingCartForGift.Visible = false;
            }
            else
            {
                rptShoppingCartForGift.DataSource = PurchaseOrder.ShoppingCart.GiftItems;
                rptShoppingCartForGift.DataBind();
                if (PurchaseOrder.ShoppingCart.CartItems.Count <= 0)
                {
                    pnlShipping.Visible = false;
                    pnlShiptext.Visible = false;
                }
            }

            //rptShoppingCart.DataSource = PurchaseOrder.ShoppingCart.CartItems;
            //rptShoppingCart.DataBind();
            pnlShoppingCart.Visible = true;
            pnlEmptyCart.Visible = false;
            //imbCheckout.Visible = true;
        }
        else
        {
            pnlShoppingCart.Visible = false;
            pnlEmptyCart.Visible = true;
            //imbCheckout.Visible = false;
        }

        ////update the count of shopping bag
        //Label lblCartItems = Page.Master.Master.FindControl("lblCartItems") as Label;
        ////lblCartItems.Text = AutoGearSessionManager.ShoppingCart.CartItems.Count + AutoGearSessionManager.ShoppingCart.GiftItems.Count + " Items";
        //lblCartItems.Text = AutoGearSessionManager.ShoppingCart.TotalCartItem + AutoGearSessionManager.ShoppingCart.TotalGiftItem + " Items";
    }
    protected void SaveData()
    {
        ProductShipping iProductShipping = new ProductShipping(uccUPSShippingMethodDropDownList.SelectedValue.ToString(), Convert.ToDouble(lblSubTotal2.Text.Replace("$", "")), Convert.ToDouble(lblShippingHandling.Text.Replace("$", "")));

        AutoGearSessionManager.ShoppingCart = PurchaseOrder.ShoppingCart;
        AutoGearSessionManager.ProductShipping = PurchaseOrder.ProductShipping;
        //AutoGearSessionManager.ProductShipping = iProductShipping;
        AutoGearSessionManager.StateTax = PurchaseOrder.ProductTax;
        AutoGearSessionManager.Coupon = PurchaseOrder.Coupon;
    }
    protected bool CalculateShippingCost()
    {
        Address ShipFromAddress = new Address(tbxBillingFirstName.Text.Trim(), tbxBillingLastName.Text.Trim(), tbxBillingAddressLine1.Text.Trim(), tbxBillingAddressLine2.Text.Trim(), tbxBillingCity.Text.Trim(), uccBillingState.SelectedItem.Value, uccBillingCountry.SelectedItem.Value, tbxBillingZipCode.Text.Trim(), tbxBillingPhone.Text.Trim(), tbxBillingPhone2.Text.Trim(), tbxBillingEmailAddress.Text.Trim());
        Address ShippingAddress = new Address(tbxShippingFirstName.Text.Trim(), tbxShippingLastName.Text.Trim(), tbxShippingAddressLine1.Text.Trim(), tbxShippingAddressLine2.Text.Trim(), tbxShippingCity.Text.Trim(), uccShippingState.SelectedItem.Value, uccShippingCountry.SelectedItem.Value, tbxShippingZipCode.Text.Trim(), tbxShippingPhone.Text.Trim(),string.Empty, tbxShippingEmailAddress.Text.Trim());
       
        PurchaseOrder.ProductShipping.ProductTotalWeight = PurchaseOrder.ShoppingCart.TotalWeight;
        PurchaseOrder.ProductShipping.ProductShippingMethod = uccUPSShippingMethodDropDownList.SelectedItem.Value;
        PurchaseOrder.ProductShipping.CalculateShippingCost(ShipFromAddress, ShipFromAddress, ShippingAddress, uccUPSShippingMethodDropDownList.SelectedItem.Value);
        return true;
    }

    protected void rptShoppingCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            CartItem cartItem = (CartItem)e.Item.DataItem;

            Image imgItemImage = (Image)e.Item.FindControl("imgItemImage");
            imgItemImage.ImageUrl = ImageResizer.CheckImageMissing(cartItem.Product.ProductImageSmallThumbnail, AutoGear.BLL.SiteSettings.NoImageSmallThumbnailUrl);

            HyperLink hlkItem = (HyperLink)e.Item.FindControl("hlkItem");
            hlkItem.NavigateUrl = cartItem.Product.ProductUrl;
            hlkItem.Text = cartItem.Product.ProductName;

            Label lblItemNumber = (Label)e.Item.FindControl("lblItemNumber");
            lblItemNumber.Text = "Item Number: " + cartItem.Product.ItemNumber;

            Label lblItemPrice = (Label)e.Item.FindControl("lblItemPrice");
            if (string.IsNullOrEmpty(SupplierId))
            {
                if (cartItem.Product.StandardCost > 0)
                {
                    lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.Product.StandardCost + cartItem.Product.AdditionalPrice);
                }
                else
                {
                    lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.Product.ProductPrice + cartItem.Product.AdditionalPrice);
                }
            }
            else
            {
                lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.UnitPrice);
            }

            Label lblQuantity = (Label)e.Item.FindControl("lblQuantity");
            lblQuantity.Text = cartItem.Quantity.ToString();

            Label lblItemTotal = (Label)e.Item.FindControl("lblItemTotal");
            lblItemTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.ItemTotal);

            Button imbItemUpdate = (Button)e.Item.FindControl("imbItemUpdate");
            if (imbItemUpdate != null)
            {
                imbItemUpdate.CommandArgument = e.Item.ItemIndex.ToString();
            }
        }
        else if (e.Item.ItemType == ListItemType.Footer)
        {
            Label lblSubTotal = (Label)e.Item.FindControl("lblSubTotal");
            lblSubTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(PurchaseOrder.ShoppingCart.SubTotal);
        }
    }

    protected void rptShoppingCartForGift_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            GiftItem giftItem = (GiftItem)e.Item.DataItem;

            Label lblToName = (Label)e.Item.FindControl("lblToName");
            lblToName.Text = giftItem.ToName;

            Label lblToEmail = (Label)e.Item.FindControl("lblToEmail");
            lblToEmail.Text = giftItem.ToEmailAddress;

            Label lblItemPrice = (Label)e.Item.FindControl("lblItemPrice");
            lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(giftItem.UnitPrice);

            Label lblQuantity = (Label)e.Item.FindControl("lblQuantity");
            lblQuantity.Text = giftItem.Quantity.ToString();


            Label lblItemTotal = (Label)e.Item.FindControl("lblItemTotal");
            lblItemTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(giftItem.ItemTotal);
        }
        else if (e.Item.ItemType == ListItemType.Footer)
        {
            Label lblSubTotal = (Label)e.Item.FindControl("lblSubTotal");
            lblSubTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(PurchaseOrder.ShoppingCart.GiftSubTotal);
        }
    }
    protected CartItem UpdateCartItemToShoppingCart(int qty, Product product, string MetalType, string GiftWrapper)
    {
        ShoppingCart shoppingcart = AutoGearSessionManager.ShoppingCart;
        CartItem cartItem = new CartItem(product, qty, MetalType, GiftWrapper);
        shoppingcart.UpdateCartItem(cartItem);
        AutoGearSessionManager.ShoppingCart = shoppingcart;
        return cartItem;
    }

    protected void UpdateGiftItemToShoppingCart(string giftId, int qty)
    {
        ShoppingCart shoppingcart = AutoGearSessionManager.ShoppingCart;

        GiftItem giftItem = shoppingcart.FindGiftItemByGiftId(giftId);
        giftItem.Quantity = qty;

        shoppingcart.UpdateGiftItem(giftItem);
        AutoGearSessionManager.ShoppingCart = shoppingcart;
    }

    protected void uccBillingState_SelectedIndexChanged(object sender, EventArgs e)
    {
        //PurchaseOrder.ProductTax = StateTax.GetStateTaxByStateName(uccBillingState.SelectedItem.Text);

        //CalculateAmounts();
        //SaveData();


        BindTax();
        BindGrossTotal();
        SaveData();

    }

    CreditCard CurrentCC;
    int UsedGiftCertificateId = 0;
    ProductPurchaseOrder CurrentOrder;
    PaymentStatus CurrentPaymentStatus;


    protected void PlaceOrderOnline_Click(object sender, EventArgs e)
    {
        if (!ValidatePOBox())
        {
            uccResponseMessage.SetFailMessage("Shipping address may not contain PO BOX.");
            uccResponseMessage.Visible = true;
        }
        else
        {
            #region Save Coupon
            string couponName = tbxCouponNumber.Text.Trim();
            if (!string.IsNullOrEmpty(couponName))
            {
                Coupon coupon = Coupon.Load(couponName);
                if (coupon != null)
                {
                    if (!string.IsNullOrEmpty(SupplierId))
                    {
                        if (coupon.PartnerId != -1)
                        {
                            if (coupon.PartnerId == _PartnerID && DateTime.Now < coupon.ExpireDate)
                            {
                                this.PurchaseOrder.Coupon = coupon;
                                AutoGearSessionManager.Coupon = coupon;
                            }
                        }
                        else
                        {
                            if (DateTime.Now < coupon.ExpireDate)
                            {
                                this.PurchaseOrder.Coupon = coupon;
                                AutoGearSessionManager.Coupon = coupon;
                            }

                        }
                    }
                    else
                    {
                        if (DateTime.Now < coupon.ExpireDate && coupon.PartnerId.ToString() == "-1")
                        {
                            this.PurchaseOrder.Coupon = coupon;
                            AutoGearSessionManager.Coupon = coupon;
                        }
                    }
                }
            }



            #endregion
            double PaymentAmount = Convert.ToDouble(ViewState["FinalTotalPrice"]);
            double PaymentByCreditCard = 0, PaymentByGiftCertificate = 0;
            ProductPurchaseOrder order = null;

            bool PaymentComplete = false;

            if (Page.IsValid)
            {
                try
                {
                    #region Save Billing & Shipping Addresses
                    AutoGearSessionManager.BillingAddress = new AutoGear.BLL.Address(tbxBillingFirstName.Text, tbxBillingLastName.Text, tbxBillingAddressLine1.Text, tbxBillingAddressLine2.Text, tbxBillingCity.Text, uccBillingState.SelectedValue, uccBillingCountry.SelectedValue, tbxBillingZipCode.Text, tbxBillingPhone.Text, tbxBillingPhone2.Text, tbxBillingEmailAddress.Text);
                    AutoGearSessionManager.ShippingAddress = new AutoGear.BLL.Address(tbxShippingFirstName.Text, tbxShippingLastName.Text, tbxShippingAddressLine1.Text, tbxShippingAddressLine2.Text, tbxShippingCity.Text, uccShippingState.SelectedValue, uccShippingCountry.SelectedValue, tbxShippingZipCode.Text, tbxShippingPhone.Text, string.Empty, tbxShippingEmailAddress.Text);
                    #endregion
                    string substitute = string.Empty;
                    if (Session["check"] != null)
                        substitute = Session["check"].ToString();
                    else
                        substitute = string.Empty;
                    string requestdate = string.Empty;
                    if (!string.IsNullOrEmpty(tbxRequestDeliveryDate.Text))
                        requestdate = tbxRequestDeliveryDate.Text;
                    int SPId;
                    string salesName = string.Empty;
                    if (Session["SPId"] != null)
                    {
                        SPId = Convert.ToInt32(Session["SPId"]);
                        TblSalesPerson sales = TblSalesPerson.GetTblSalesPersonBySPId(SPId);
                        if (sales != null)
                        {
                            if (sales.FirstName != null)
                                salesName = sales.FirstName.Substring(0, 1) + ".";
                            if (sales.LastName != null)
                                salesName += sales.LastName;

                        }
                    }
                    else
                        SPId = 0;
                    order = CurrentOrder = new ProductPurchaseOrder(AutoGearSessionManager.ShoppingCart, AutoGearSessionManager.ProductShipping, AutoGearSessionManager.StateTax, AutoGearSessionManager.BillingAddress, AutoGearSessionManager.ShippingAddress, null, AutoGearSessionManager.Coupon, "", "", "", requestdate, 0, substitute, SPId, salesName);
                    order.SpecialInstruction = HttpContext.Current.Server.HtmlEncode(tbxComment.Text);
                    order.GIftCardMessage = HttpContext.Current.Server.HtmlEncode(tbxGiftMessage.Text);
                    //order.OfficeUse = HttpContext.Current.Server.HtmlEncode(tbxOfficeUseOnly.Text);
                    order.IsResidential = cbxResidential.Checked;
                    order.Substitute = substitute;
                    order.SPId = _PartnerID;
                    order.SPName = "_PartnerId";
                    if (string.IsNullOrEmpty(SupplierId))
                    {
                        order.Create();
                    }
                    else
                    {
                        order.CreatePartnerOrder();
                    }
                    AutoGearSessionManager.OrderNumber = order.OrderNumber;

                    #region Payment By Credit Card
                    if (DropDownListPaymentType.SelectedValue == "2")
                    {
                        PaymentWithCreditCard(PaymentAmount);
                        PaymentByCreditCard = PaymentAmount;
                        PaymentComplete = true;
                        order.PaymentType = PaymentType.CreditCard;
                    }
                    #endregion

                    PaymentStatus status = CurrentPaymentStatus;

                    #region Update Order Status

                    if (status.Message.ToLower().Contains("success"))
                    {
                        order.OrderStatus = OrderStatus.CCSuccess;
                        order.CreditCardAmount = PaymentByCreditCard;
                    }
                    else
                    {
                        //uccResponseMessage.SetFailMessage(status.Message);
                        order.OrderStatus = OrderStatus.CCFail;
                        order.CreditCardAmount = 0;
                        //Response.Redirect(AutoGear.BLL.CustomSiteMap.Receipt);
                    }

                    #endregion

                    #region Commit order details
                    order.CreditCard = AutoGearSessionManager.Card;
                    order.GiftCertificateID = UsedGiftCertificateId;
                    //order.CreditCardAmount = PaymentByCreditCard;
                    order.GiftCertificateAmount = PaymentByGiftCertificate;
                    order.ShippingStatus = ShippingStatus.NotShipped;
                    order.OrderStatusMessage = status.Message;
                    order.OrderStatusCode = status.StatusCode;
                    order.OrderDate = DateTime.Now;
                    order.IsMultipleShip = false;
                    order.OfficeUse = status.RequestId;

                    foreach (CartItem item in order.ShoppingCart.CartItems)
                    {
                        item.Product.ReduceStock(item.Quantity);
                        if (StockAlert.IsStockAlert(item.Product.ProductId))
                        {
                            StockAlert alert = StockAlert.Load(item.Product.ProductId);
                            StockAlert.SendStockAlertEmail(alert);
                        }
                    }
                    //order.CouponDiscount = PurchaseOrder.CouponDiscount;
                    order.Update();
                    #endregion
                   
                    #region Gift Certificate Email
                    if (order.ShoppingCart.GiftItems.Count > 0)
                    {
                        Email.SendGiftCertificateEmail(order);
                    }

                    #endregion

                    AutoGearSessionManager.OrderNumber = order.OrderNumber;                   

                    if (String.IsNullOrEmpty(SupplierId))
                    {
                        Email.SendInvoiceEmail(order, string.Empty);
                    }
                    else
                    {
                        string imgUrl = SiteGlobals.BaseUrl + "upload/partner-images/" + _BrandImageUrl;
                        Email.SendInvoiceEmail(order, imgUrl);
                    }

                    AutoGearSessionManager.ShoppingCart = null;
                    AutoGearSessionManager.ProductShipping = null;
                    AutoGearSessionManager.StateTax = null;
                    AutoGearSessionManager.Coupon = null;
                    AutoGearSessionManager.CheckoutSteps = CheckoutSteps.OrderSummary;
                    Response.Redirect(string.IsNullOrEmpty(SupplierId) ? CustomSiteMap.Receipt : "~/partner/" + SupplierId + "/receipt.aspx");
                }
                catch (ECommerceException ex)
                {
                    uccResponseMessage.SetFailMessage(ex.Message);
                    if (order != null && order.OrderId > 0)
                    {
                        order.Delete();
                    }
                    if (CurrentCC != null && CurrentCC.CardId > 0)
                        CurrentCC.Delete();
                }
              
            }
        }
    }

    private TblGiftCertificate PaymentWithGiftCertificate(double PaymentAmount, bool payOnlyUsingGiftCertificate, out double amountPaid)
    {
        TblGiftCertificate CurrentGiftCertificate = TblGiftCertificate.GetGiftCertificateByCode(TextBoxGiftCertificateCode.Text);
        amountPaid = 0;

        if (CurrentGiftCertificate != null)
        {

            #region Check GiftCertificate

            if ((DateTime)CurrentGiftCertificate.DateExpired < DateTime.Now)
            {
                throw new ECommerceException("Gift Certificate expired");
            }
            else if (!CurrentGiftCertificate.IsActive)
            {
                throw new ECommerceException("Gift Certificate is inactive");
            }
            else
            {
                // Do Nothing
            }


            #endregion

            if (CurrentGiftCertificate.CurrentBalance >= PaymentAmount)
            {
                amountPaid = PaymentAmount;

            }
            else
            {
                if (payOnlyUsingGiftCertificate)
                    throw new ECommerceException("Not enough balance in gift certificate. Please pay using your credit card.");
                else
                {
                    amountPaid = CurrentGiftCertificate.CurrentBalance;
                }
            }
        }
        else
        {
            throw new ECommerceException("Sorry. The gift certificate code is not valid.");
        }

        CurrentGiftCertificate.CurrentBalance = CurrentGiftCertificate.CurrentBalance - amountPaid;
        return CurrentGiftCertificate;
    }

    private void PaymentWithCreditCard(double PaymentAmount)
    {
        try
        {
            if (PaymentAmount > 0)
            {
                string ddLCardType = string.Empty, firstdigit = string.Empty;
                firstdigit = tbxCardNumber.Text.Substring(0, 1);
                if (!string.IsNullOrEmpty(firstdigit))
                {
                    if (firstdigit == "4")
                        ddLCardType = "Visa";
                    else if (firstdigit == "3")
                        ddLCardType = "American Express";
                    else if (firstdigit == "5")
                        ddLCardType = "MasterCard";
                    else if (firstdigit == "6")
                        ddLCardType = "Discover";
                    else
                        ddLCardType = string.Empty;
                }

                if (!string.IsNullOrEmpty(ddLCardType))
                {

                    #region Save Credit Card Details
                    DateTime expireDate = DateTime.Parse(ddlMonth.SelectedValue + "/01/" + ddlYear.SelectedValue);
                    expireDate = expireDate.AddMonths(1).AddDays(-1);
                    CreditCard creditCard = CurrentCC = new CreditCard(ddLCardType, tbxCardNumber.Text, tbxSecurityCode.Text, expireDate);
                    creditCard.Save();
                    AutoGearSessionManager.Card = creditCard;
                    #endregion

                    #region Initiate Payment Gateway Transaction
                    CurrentPaymentStatus = new PaymentStatus("Transaction success", "TEST", "TEST", "TEST");
                    #endregion

                    string code = "1";
                    string response = "No Payment Gateway integrated";


                }
                else
                {
                    uccResponseMessage.Visible = true;
                    uccResponseMessage.SetFailMessage("Invalid Card No.");
                }
            }
        }
        catch
        {
            CurrentPaymentStatus = new PaymentStatus("Transaction Failed", "An internal error occured", "0");
        }
    }
    protected void uccUPSShippingMethodDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {

        PurchaseOrder.ProductShipping.ProductShippingMethod = uccUPSShippingMethodDropDownList.SelectedItem.Value;
        CalculateAmounts();
        SaveData();
    }
    protected void cvUPSShippingMethodDropDownList_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = this.CalculateShippingCost();
        if (args.IsValid)
        {
            UPSShippingMethodResponseMessage.Visible = false;
        }
        else
        {
            UPSShippingMethodResponseMessage.SetFailMessage(AutoGearCommonMessage.ShipmentCostGeneralFailed);
            UPSShippingMethodResponseMessage.Visible = true;
        }
    }
    protected void tbxCouponNumber_TextChanged(object sender, EventArgs e)
    {

        string couponName = tbxCouponNumber.Text.Trim();
        Coupon coupon = Coupon.Load(couponName);

        if (coupon != null)
        {
            if (!string.IsNullOrEmpty(SupplierId))
            {
                if (coupon.PartnerId == _PartnerID && DateTime.Now < coupon.ExpireDate)
                {
                    this.PurchaseOrder.Coupon = coupon;
                    CalculateAmounts();
                    SaveData();
                }
                else
                {
                    lblCuponMessage.Text = "Coupon expired!";
                }
            }
            else
            {
                if (DateTime.Now < coupon.ExpireDate && coupon.PartnerId.ToString() == "-1")
                {
                    this.PurchaseOrder.Coupon = coupon;
                    CalculateAmounts();
                    SaveData();
                }
                else
                {
                    lblCuponMessage.Text = "Coupon expired!";
                }
            }



        }
        else
        {
            lblCuponMessage.Text = "Invalid/Expired Coupon Number!";
        }
    }
    protected void DropDownListPaymentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownListPaymentType.SelectedValue == "2")
        {
            pnlGiftCertificateEntry.Visible = false;
            pnlCreditCardEntry.Visible = true;
        }
        if (DropDownListPaymentType.SelectedValue == "1")
        {
            pnlGiftCertificateEntry.Visible = true;
            pnlCreditCardEntry.Visible = false;
        }
        if (DropDownListPaymentType.SelectedValue == "3")
        {
            pnlGiftCertificateEntry.Visible = true;
            pnlCreditCardEntry.Visible = true;
        }
    }
    protected void ddlShipp_SelectedIndexChanged(object sender, EventArgs e)
    {
        Load_shipping_info(false);
    }
    protected void tbxShippingAddressLine2_TextChanged(object sender, EventArgs e)
    {
        if (!ValidatePOBox())
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "ShowPoBoxErr();", true);
        }
    }
    protected void tbxShippingAddressLine1_TextChanged(object sender, EventArgs e)
    {
        if (!ValidatePOBox())
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "ShowPoBoxErr();", true);
        }

    }

    private bool ValidatePOBox()
    {
        bool returnVal = true;
        string s1 = tbxShippingAddressLine1.Text.ToString();
        List<string> poboxList = new List<string>();
        poboxList.Add("PO BOX");
        poboxList.Add("P.O. Box");
        poboxList.Add("PO Box");
        poboxList.Add("P.O. BOX");
        poboxList.Add("PO Box");
        poboxList.Add("PO box");
        poboxList.Add("Po box");
        poboxList.Add("P.O.BOX");

        foreach (string compareitem in poboxList)
        {
            if (s1.Contains(compareitem))
            {
                returnVal = false;
            }
        }
        return returnVal;
    }
    protected void lnkbApply_Click(object sender, EventArgs e)
    {
        #region Save Coupon
        string couponName = tbxCouponNumber.Text.Trim();
        Coupon coupon = Coupon.Load(couponName);

        if (coupon != null)
        {
            if (!string.IsNullOrEmpty(SupplierId))
            {
                if (coupon.PartnerId != -1)
                {

                    if (coupon.PartnerId == _PartnerID && DateTime.Now < coupon.ExpireDate)
                    {
                        if (coupon.MinimumAmount <= Convert.ToDouble(PurchaseOrder.ShoppingCart.SubTotal + PurchaseOrder.ShoppingCart.GiftSubTotal))
                        {
                            this.PurchaseOrder.Coupon = coupon;
                            AutoGearSessionManager.Coupon = coupon;
                            CalculateAmounts();
                            lnkbCancel.Visible = true;
                            lnkbApply.Visible = false;
                        }
                        else
                        {
                            tbxCouponNumber.Text = string.Empty;
                            lblCuponMessage.Text = "Must Match Minimum Order Amount!";
                        }
                    }
                    else { lblCuponMessage.Text = "Invalid Coupon!"; tbxCouponNumber.Text = string.Empty; }
                }
                else
                {
                    if (DateTime.Now < coupon.ExpireDate && coupon.PartnerId.ToString() == "-1")
                    {
                        if (coupon.MinimumAmount <= Convert.ToDouble(PurchaseOrder.ShoppingCart.SubTotal + PurchaseOrder.ShoppingCart.GiftSubTotal))
                        {
                            this.PurchaseOrder.Coupon = coupon;
                            AutoGearSessionManager.Coupon = coupon;
                            CalculateAmounts();
                            lnkbCancel.Visible = true;
                            lnkbApply.Visible = false;
                        }
                        else
                        {
                            tbxCouponNumber.Text = string.Empty;
                            lblCuponMessage.Text = "Must Match Minimum Order Amount!";
                        }
                    }
                    else { lblCuponMessage.Text = "Invalid Coupon!"; tbxCouponNumber.Text = string.Empty; }

                }

            }
            else
            {
                if (DateTime.Now < coupon.ExpireDate && coupon.PartnerId.ToString() == "-1")
                {
                    if (coupon.MinimumAmount <= Convert.ToDouble(PurchaseOrder.ShoppingCart.SubTotal + PurchaseOrder.ShoppingCart.GiftSubTotal))
                    {
                        this.PurchaseOrder.Coupon = coupon;
                        AutoGearSessionManager.Coupon = coupon;
                        CalculateAmounts();
                        lnkbCancel.Visible = true;
                        lnkbApply.Visible = false;
                    }
                    else
                    {
                        tbxCouponNumber.Text = string.Empty;
                        lblCuponMessage.Text = "Must Match Minimum Order Amount!";
                    }
                }
                else { lblCuponMessage.Text = "Invalid Coupon!"; tbxCouponNumber.Text = string.Empty; }
            }

        }
        else { lblCuponMessage.Text = "Invalid Coupon!"; tbxCouponNumber.Text = string.Empty; }
        #endregion
    }
    protected void lnkbCancel_Click(object sender, EventArgs e)
    {
        //PurchaseOrder.CouponDiscount = 0.00;
        AutoGearSessionManager.Coupon = null;
        tbxCouponNumber.Text = "";
        lblCuponMessage.Text = "";
        CalculateAmounts();
        lnkbCancel.Visible = false;
        lnkbApply.Visible = true;
    }


    protected void tbxBillingCity_TextChanged(object sender, EventArgs e)
    {
        BindTax();
        BindGrossTotal();
        SaveData();
    }


}
